import React, {PropsWithChildren, useState} from 'react'
import {QINIU_IMAGE_HOST, QINIU_UPLOAD_URL, withSuccessUploadImage} from "../utils/UploadUtils";
import {ImagePreview, Uploader} from "@nutui/nutui-react-taro";
import qiniuUploadStore from "../store/QiniuUploadStore";
import {observer} from "mobx-react-lite";
import Taro from "@tarojs/taro";

export interface QiniuUploaderProps extends PropsWithChildren {
    value:string[]
    onChange:(value:string[])=>void
    label?:string
    multiple?:boolean
}

const QiniuImageUploader: React.FC<QiniuUploaderProps> = ({value,onChange,label,multiple}) => {
    const [imagePreviewIndex,setImagePreviewIndex] = useState<number>()
    return <>
        <Uploader multiple={multiple??false} url={QINIU_UPLOAD_URL}
                  value={value.map(k=>withSuccessUploadImage(k, `${QINIU_IMAGE_HOST}${k}`))}
                  disabled={!qiniuUploadStore.token}
                  data={{token: qiniuUploadStore.token}}
                  uploadLabel={label}
                  onSuccess={(param)=>{
                      let response = param.responseText as any;
                      let key = JSON.parse(response.data).key;
                      const arr = Array.from(value)
                      if (arr.indexOf(key)==-1){
                          arr.push(key)
                          onChange(arr)
                      }
                      Taro.hideLoading()
                      Taro.showToast({
                          title:"上传成功",
                          icon:"success",
                      })
                  }}
                  onDelete={(f,_)=>{
                      onChange(value.filter(it=>f.uid!==it))
                  }}
                  onStart={_=>{
                      Taro.showLoading({
                          title:"上传中"
                      })
                  }}
                  onFailure={()=>{
                      Taro.hideLoading()
                      Taro.showToast({
                          title:"上传失败",
                          icon:"error",
                      })
                  }}
                  onFileItemClick={(_,index)=>{
                      setImagePreviewIndex(index)
                  }}
                  mediaType={["image"]}/>
        <ImagePreview value={imagePreviewIndex} onChange={()=>{
            setImagePreviewIndex(imagePreviewIndex)
        }} visible={imagePreviewIndex!==undefined} images={value.map(it=> {
            return {
                src:`${QINIU_IMAGE_HOST}${it}`
            }
        })} onClose={()=>{
            setImagePreviewIndex(undefined)
        }} closeIcon
        closeIconPosition={"bottom"}/>
    </>
}

export default observer(QiniuImageUploader)


